﻿using System;
using Microsoft.Xna.Framework;
using RhythmComet;

namespace FMOD
{
#if !XBOX
    public class fmodBeatDetectorManager : GameComponent, IBeatManager
    {
        #region Fields and properties

        RhythmCometGame game;
        IBeatDetector[] bands;
        int totalBands;
        int louderBand;

        public SubBands LouderBand
        {
            get { return (SubBands)louderBand; }
        }

        public int TotalBands
        {
            get { return totalBands; }
        }

        public IBeatDetector[] Band
        {
            get { return bands; }
        }

        public float AverageEnergy
        {
            get 
            {
                float average = 0.0f;
                for (int i = 0; i < totalBands; i++)
                {
                    average += bands[i].Energy;
                }
                average /= 7.0f;
                return average;
            }
        }
        #endregion

        public fmodBeatDetectorManager(Game game, int total) : base(game)
        {
            this.game = (RhythmCometGame)game;
            bands = new fmodBeatDetector[total];
            totalBands = 0;
        }

        public void AddBand(int begin, int end, float deviation, float spawnTime, float timeBufferLength)
        {
            if (totalBands < bands.Length)
            {
                bands[totalBands++] = new fmodBeatDetector(this.game, begin, end, deviation, spawnTime, timeBufferLength);
            }
        }

        public override void Initialize()
        {
            base.Initialize();
        }

        public override void Update(GameTime gameTime)
        {
            float max = 0.0f;
            louderBand = 7;

            for (int i = 0; i < totalBands; i++)
            {
                
                bands[i].Update(gameTime);
                if (bands[i].Energy > max && i > 2 && i < 5)
                {
                    louderBand = i;
                    max = bands[i].Energy;
                }
            
            }
            base.Update(gameTime);
        }

        public void Reset()
        {
            for (int i = 0; i < totalBands; i++)
            {
                bands[i].Reset();
            }
        }
    }
#endif
}
